
using System;
using Gtk;
using AtDevice;

namespace GtkControls
{
    
    public class TrayIcon
    {
        private Gtk.Window _mainWindow;
        private StatusIcon _statusIcon = new StatusIcon();
        
        public TrayIcon(Gtk.Window mainWindow)
        {
            _mainWindow = mainWindow;
            ShowIcon();
            
            DeviceHandler.DeviceOpened += delegate(AtDevice.AtDevice dev) {
                dev.GetInterface<IHuaweiInterface>().FlowUpdated += FlowUpdated;
            };
        }
        
        private string GetSignalStrength()
        {
            IGSMInterface gsmI = DeviceHandler.Get().GetGSMInterface();
            double signal = 0.0;
            
            try {
                signal = gsmI.GetSignal() / 100.0;
            } catch(UnknownSignalException) { }
            
            int nbars = AtUtils.GetSignalNumberOfBars(signal);
            
            // Example: [▯▯   ] (32%)
            string strength = String.Format("[{0}{1}] ({2}%)", new String('▯', nbars),
                                                               new String(' ', (int)((5 - nbars)*1.5)),
                                                               signal*100);
            return strength;
        }
        
        private void FlowUpdated(int uptime, int dlSpeed, int ulSpeed, long dlBytes, long ulBytes)
        {
            Gtk.Application.Invoke(delegate {
                _statusIcon.Tooltip = String.Format("{0}\n" +
                                                    "D: {1}/s U: {2}/s",
                                                    GetSignalStrength(),
                                                    StringUtils.FormatBytes(dlSpeed),
                                                    StringUtils.FormatBytes(ulSpeed));
            });
        }

        private Gdk.Pixbuf RenderIcon()
        {
            // TODO Add signal strength indication to the icon
            return Gdk.Pixbuf.LoadFromResource("Resources.signal.png");
        }

        private void ShowIcon()
        {
            _statusIcon.Pixbuf = RenderIcon();
            _statusIcon.PopupMenu += HandlePopupMenu;
            _statusIcon.Tooltip = "<not connected>";
            _statusIcon.Activate += delegate { _mainWindow.Visible = !_mainWindow.Visible; };
            _statusIcon.Visible = true;
        }
        
        private void HandlePopupMenu(object o, PopupMenuArgs args)
        {
            Menu popupMenu = new Menu();
            popupMenu.AppendMenuItem("Quit", delegate { 
                DeviceHandler.Close();
                Gtk.Application.Quit();
            });
            popupMenu.ShowAll();
            popupMenu.Popup();
        }
    }
}
